#include "changepassworddialog.h"
#include "ui_changepassworddialog.h"
#include "logmanager.h"
#include <QRegularExpression>
#include <QMessageBox>
#include <QCryptographicHash>

ChangePasswordDialog::ChangePasswordDialog(QWidget *parent, const QSqlRecord &userRecord)
    : QDialog(parent)
    , ui(new Ui::ChangePasswordDialog)
    , m_passwordChanged(false)
{
    ui->setupUi(this);

    // 设置窗口属性
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    setModal(true);

    // 检查记录是否有效（通过检查字段数量或特定字段是否存在）
    if (userRecord.count() > 0 && !userRecord.value("username").isNull()) {
        QString username = userRecord.value("username").toString();
        QString userID = userRecord.value("user_id").toString();
        setUserInfo(username, userID);
    } else {
        // 如果记录无效，设置默认值
        ui->labelUsernameValue->setText("无效记录");
        ui->labelUserIDValue->setText("-");
    }

    // 连接信号槽
    connect(ui->lineEditNewPassword, &QLineEdit::textChanged, this, &ChangePasswordDialog::onPasswordTextChanged);
    connect(ui->lineEditConfirmPassword, &QLineEdit::textChanged, this, &ChangePasswordDialog::validateInputs);
    connect(ui->lineEditOldPassword, &QLineEdit::textChanged, this, &ChangePasswordDialog::validateInputs);

    // 初始验证
    validateInputs();

    // 记录日志
    LogManager::logSystem("修改密码对话框", "修改密码对话框初始化完成");
}

ChangePasswordDialog::~ChangePasswordDialog()
{
    delete ui;
}

void ChangePasswordDialog::setUserInfo(const QString &username, const QString &userID)
{
    ui->labelUsernameValue->setText(username);
    ui->labelUserIDValue->setText(userID);
}

QString ChangePasswordDialog::getOldPassword() const
{
    return m_oldPassword;
}

QString ChangePasswordDialog::getNewPassword() const
{
    return m_newPassword;
}

bool ChangePasswordDialog::isPasswordChanged() const
{
    return m_passwordChanged;
}

void ChangePasswordDialog::onPasswordTextChanged()
{
    QString password = ui->lineEditNewPassword->text();
    int strength = calculatePasswordStrength(password);

    // 更新进度条
    ui->progressBarStrength->setValue(strength);

    // 更新强度文本
    QString strengthText;

    if (strength < 25) {
        strengthText = "非常弱";
    } else if (strength < 50) {
        strengthText = "弱";
    } else if (strength < 75) {
        strengthText = "中等";
    } else {
        strengthText = "强";
    }

    ui->labelStrengthText->setText(QString("密码强度: %1").arg(strengthText));
}

void ChangePasswordDialog::validateInputs()
{
    QString oldPassword = ui->lineEditOldPassword->text();
    QString newPassword = ui->lineEditNewPassword->text();
    QString confirmPassword = ui->lineEditConfirmPassword->text();

    bool valid = true;

    // 检查原密码是否为空
    if (oldPassword.isEmpty()) {
        valid = false;
    }

    // 检查新密码是否符合规则
    if (!validatePasswordRules(newPassword)) {
        valid = false;
    }

    // 检查确认密码是否匹配
    if (newPassword != confirmPassword) {
        valid = false;
    }

    ui->pushButtonOK->setEnabled(valid);
}

int ChangePasswordDialog::calculatePasswordStrength(const QString &password)
{
    int strength = 0;

    if (password.length() >= 8) strength += 25;
    if (password.length() >= 12) strength += 15;

    QRegularExpression upperCase("[A-Z]");
    QRegularExpression lowerCase("[a-z]");
    QRegularExpression digit("[0-9]");
    QRegularExpression specialChar("[^A-Za-z0-9]");

    if (password.contains(upperCase)) strength += 20;
    if (password.contains(lowerCase)) strength += 20;
    if (password.contains(digit)) strength += 20;
    if (password.contains(specialChar)) strength += 20;

    return qMin(strength, 100);
}

bool ChangePasswordDialog::validatePasswordRules(const QString &password)
{
    // 基本长度检查
    if (password.length() < 8) {
        return false;
    }

    // 复杂度检查
    QRegularExpression upperCase("[A-Z]");
    QRegularExpression lowerCase("[a-z]");
    QRegularExpression digit("[0-9]");

    return (password.contains(upperCase) &&
            password.contains(lowerCase) &&
            password.contains(digit));
}

// 重写accept函数进行最终验证
void ChangePasswordDialog::accept()
{
    QString oldPassword = ui->lineEditOldPassword->text();
    QString newPassword = ui->lineEditNewPassword->text();
    QString confirmPassword = ui->lineEditConfirmPassword->text();

    // 最终验证
    if (oldPassword.isEmpty()) {
        QMessageBox::warning(this, "警告", "请输入原密码");
        return;
    }

    if (!validatePasswordRules(newPassword)) {
        QMessageBox::warning(this, "警告",
                            "新密码不符合要求！\n要求：至少8位，包含大小写字母和数字");
        return;
    }

    if (newPassword != confirmPassword) {
        QMessageBox::warning(this, "警告", "新密码与确认密码不一致");
        return;
    }

    // 设置结果
    m_oldPassword = oldPassword;
    m_newPassword = newPassword;
    m_passwordChanged = true;

    // 记录日志
    LogManager::logOperation(-1, "修改密码",
                           QString("用户通过对话框修改密码，用户: %1")
                           .arg(ui->labelUsernameValue->text()), "", "");

    QDialog::accept();
}
